// iss-wallpaper.obj.js
const ApiResponse = require('../common/api-response.js')
// 在文件顶部添加 WallpaperImageService 的引入
const WallpaperImageService = require('./wallpaper-image.service.js')

const BaseService = require('./base.service.js')
const UserController = require('./user.controller.js')

class WallpaperClassifyService extends BaseService {
  constructor({cloudObject}) {
    super({ cloudObject }) // 调用父类构造函数
    this.collectionName = 'iss-wallpaper-classify'
	this.userController = new UserController(cloudObject)
	// 注入 WallpaperImageService 实例
	this.wallpaperImageService = new WallpaperImageService({cloudObject})
	
  }

  // 获取集合引用
  get collection() {
    return this.db.collection(this.collectionName)
  }

  /**
   * 构建查询条件
   * @param {Object} query - 查询参数
   * @returns {Object} 查询条件
   */
  _buildWhereConditions(query) {
    const whereConditions = {}

    if (query.name) {
      whereConditions.name = new RegExp(query.name, 'i')
    }

    if (query.select !== undefined) {
      whereConditions.select = query.select
    }

    if (query.enable !== undefined) {
      whereConditions.enable = query.enable
    }

    if (Array.isArray(query.updateTime) && query.updateTime.length === 2) {
      whereConditions.updateTime = this.dbCmd.and(
        this.dbCmd.gte(query.updateTime[0]),
        this.dbCmd.lte(query.updateTime[1])
      )
    }

    return whereConditions
  }

  _before() {
    // 可选权限验证逻辑
  }

  /**
   * 分页查询分类列表
   * @param {Object} query - 查询参数
   * @returns {ApiResponse} 统一响应格式
   */
  async getList(query = {}) {
    try {
	  // 对权限进行校验
	  await this.userController.hasPermission('wcr','allin','permission')
	  
      const whereConditions = this._buildWhereConditions(query)
      const orderFiled = query.orderFiled || 'sort'
      const orderDirection = query.orderDirection || 'asc'
	  const page = query.page || 1
	  const pageSize = query.pageSize || 10

      // 执行查询
      const response = await this.collection
        .where(whereConditions)
        .orderBy(orderFiled, orderDirection)
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

      const { total } = await this.collection.where(whereConditions).count()

      return ApiResponse.success({
        total,
        list: response.data
      })
    } catch (e) {
      console.error('获取分类列表失败:', e)
      return ApiResponse.serverError(ApiResponse.ErrorMessage.SERVICE_ERROR)
    }
  }

  /**
   * 根据id获得对应壁纸分类
   * @param {string} id - 分类ID
   * @returns {ApiResponse} 统一响应格式
   */
  async doc(id) {
    try {
      if (!id) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
      }
	  
	  // 对权限进行校验
	  await this.userController.hasPermission('wcr','allin','permission')

      const response = await this.collection.doc(id).get()

      if (response.data && response.data.length === 1) {
        return ApiResponse.success(response.data[0])
      }
      return ApiResponse.notFound(ApiResponse.ErrorMessage.CLASSIFY_NOT_FOUND)
    } catch (e) {
      console.error('获取分类失败:', e)
      return ApiResponse.serverError('获取分类失败:' + e)
    }
  }

  /**
   * 检查分类名称是否已存在
   * @param {string} name - 分类名称
   * @param {string} [excludeId] - 要排除的ID
   * @returns {Promise<boolean>} 是否存在
   */
  async _checkNameExists(name, excludeId) {
    const condition = { name }
    if (excludeId) {
      condition._id = this.dbCmd.neq(excludeId)
    }

    const checkResult = await this.collection
      .where(condition)
      .count()

    return checkResult.total > 0
  }

  /**
   * 新增分类（带名称唯一性校验）
   * @param {Object} data - 分类数据
   * @returns {ApiResponse} 统一响应格式
   */
  async add(data) {
    try {
      if (!data || !data.name) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.CLASSIFY_NAME_REQUIRED)
      }
	  
	  // 对权限进行校验
	  await this.userController.hasPermission('wca','allin','permission')

      // 准备插入数据
      const insertData = {
        name: data.name.trim(),
        sort: Number(data.sort) || 0,
        picurl: (data.picurl || '').trim(),
        select: !!data.select,
        enable: !!data.enable,
        updateTime: Date.now()
      }

      // 检查分类名称是否已存在
      if (await this._checkNameExists(insertData.name)) {
        return ApiResponse.badRequest('分类名称已存在')
      }

      // 执行新增操作
      const result = await this.collection.add(insertData)

      return ApiResponse.success({
        id: result.id
      }, '分类创建成功')
    } catch (e) {
      console.error('创建分类失败:', e)

      // 处理唯一索引冲突错误
      if (e.errCode === 'DATABASE_REQUEST_FAILED' && e.message.includes('duplicate key')) {
        return ApiResponse.badRequest('分类名称已存在')
      }

      return ApiResponse.serverError('创建分类失败: ' + e.message)
    }
  }

  /**
   * 批量删除分类
   * @param {Array<string>} ids - 要删除的ID数组
   * @returns {ApiResponse} 统一响应格式
   */
  async remove(ids) {
    try {
      if (!Array.isArray(ids) || ids.length === 0) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.IDS_REQUIRED)
      }
	  
	  // 对权限进行校验
	  await this.userController.hasPermission('wcd','allin','permission')
	  
	  const res = await this.collection.where({_id: this.dbCmd.in(ids)}).get()
	  const cloudIds = res.data.map(item=>item.picurl)

      const result = await this.collection.where({
        _id: this.dbCmd.in(ids)
      }).remove()
	  
	  try{
	    // 调用 WallpaperImageService 的 deleteImage 方法删除图片
		if (cloudIds.length > 0) {
			const deleteResult = this.handleApiResponse(() => this.wallpaperImageService.deleteImage(cloudIds))
		}
	  } catch(e) {
	    console.log('图片删除失败:' + e)
	  }
	  

      if (result.deleted === 0) {
        return ApiResponse.notFound(ApiResponse.ErrorMessage.CLASSIFY_NOT_FOUND)
      }

      return ApiResponse.success({
        deleted: result.deleted
      }, '删除成功')
    } catch (e) {
      console.error('删除分类失败:', e)
      return ApiResponse.serverError('删除分类失败:' + e)
    }
  }

  /**
   * 更新分类信息（带名称唯一性校验）
   * @param {Object} data - 包含id和更新数据
   * @returns {ApiResponse} 统一响应格式
   */
  async update(data = {}) {
    try {
      if (!data || !data._id) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
      }
	  
	  // 对权限进行校验
	  await this.userController.hasPermission('wce','allin','permission')

      // 提取需要更新的数据
      const { _id, updateTime, name, ...updateData } = data

      // 名称唯一性校验
      if (name !== undefined) {
        const trimmedName = name.trim()

        if (await this._checkNameExists(trimmedName, _id)) {
          return ApiResponse.badRequest('分类名称已存在')
        }

        updateData.name = trimmedName
      }
	  // sort字段是数字类型，应该要保持为数字，因此此处要做如下处理
	  updateData.sort = updateData.sort * 1

      // 执行更新
      const result = await this.collection.where({ _id }).update(updateData)

      return ApiResponse.success({
        updated: result.updated
      }, '分类更新成功')
    } catch (e) {
      console.error('更新分类失败:', e)

      if (e.errCode === 'DATABASE_REQUEST_FAILED' && e.message.includes('duplicate key')) {
        return ApiResponse.badRequest('分类名称已存在')
      }

      return ApiResponse.serverError('更新分类失败: ' + e.message)
    }
  }

  /**
   * 切换bool类型字段状态
   * @param {string} id - 分类ID
   * @param {string} fieldName - 字段名
   * @returns {ApiResponse} 统一响应格式
   */
  async columnToggle(id, fieldName) {
    try {
      if (!id) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.ID_REQUIRED)
      }

      if (!fieldName) {
        return ApiResponse.badRequest(ApiResponse.ErrorMessage.PARAM_INCOMPLETE)
      }
	  
	  // 对权限进行校验
	  await this.userController.hasPermission('wce','allin','permission')

      // 获取当前状态
      const doc = await this.collection.doc(id).get()
      if (!doc.data || !doc.data.length) {
        return ApiResponse.notFound(ApiResponse.ErrorMessage.CLASSIFY_NOT_FOUND)
      }

      // 取反状态
      const currentValue = doc.data[0][fieldName]
      const params = { [fieldName]: !currentValue }

      const result = await this.collection.doc(id).update(params)

      if (result.updated === 0) {
        return ApiResponse.notFound('更新失败')
      }

      return ApiResponse.success({
        updated: result.updated
      }, '状态切换成功')
    } catch (e) {
      console.error('切换状态失败:', e)
      return ApiResponse.serverError('切换状态失败:' + e)
    }
  }
  
  // 校验分类名称
  async checkNameUnique(data) {
	  try {
	  	// 构建查询条件
	  	let where = {
	  	  name: data.name
	  	};
	  	
	  	// 如果是编辑操作，排除当前记录
	  	if (data._id) {
	  	  where._id = this.dbCmd.neq(data._id);
	  	}
	  	
	  	const res = await this.collection.where(where).count();
		
		if(res.total === 0) return ApiResponse.success(data, '分类名称校验通过')
		else return ApiResponse.serverError('分类名称重复')
	  } catch (error) {
	  	//TODO handle the exception
		return ApiResponse.serverError('分类名称校验异常：' + error)
	  }
    }
}

module.exports = WallpaperClassifyService